package com.buaa.aimall.userModule.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.aimall.userModule.Entity.ShoppingCartEntity;
import com.buaa.aimall.userModule.Mapper.ShoppingCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.buaa.aimall.modelModule.Service.ModelService;
import com.buaa.aimall.computeModule.Service.ComputeService;
import com.buaa.aimall.Utils.Exception.BusinessException;
import java.time.LocalDateTime;
import com.buaa.aimall.userModule.DTO.UpdateShoppingCartItemDTO;
import java.util.List;
import java.util.stream.Collectors;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.userModule.DTO.FilterShoppingCartDTO;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.buaa.aimall.modelModule.Entity.ModelEntity;
import com.buaa.aimall.computeModule.Entity.ComputeEntity;
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCartEntity> implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    
    @Autowired
    private ModelService modelService;
    
    @Autowired
    private ComputeService computeService;

    @Autowired
    private UserService userService;

    @Override
    public Boolean addToCart(ShoppingCartEntity shoppingCartEntity) {
        // 检查模型ID的存在性
        if (shoppingCartEntity.getModelID() != null && !shoppingCartEntity.getModelID().equals("")) {
            if (modelService.getById(shoppingCartEntity.getModelID()) == null) {
                throw new BusinessException("模型不存在");
            }
        }
        
        // 检查计算资源ID的存在性
        if (shoppingCartEntity.getComputeID() != null && !shoppingCartEntity.getComputeID().equals("")) {
            if (computeService.getById(shoppingCartEntity.getComputeID()) == null) {
                throw new BusinessException("算力不存在");
            }
        }
        shoppingCartEntity.setCreateTime(LocalDateTime.now());
        shoppingCartEntity.setCreator(userService.getCurrentUser().getId());
        return this.save(shoppingCartEntity);
    }

    @Override
    public Boolean updateCartItem(UpdateShoppingCartItemDTO updateDTO) {
        // 检查购物车项是否存在
        ShoppingCartEntity existingItem = this.getById(updateDTO.getId());
        if (existingItem == null) {
            throw new BusinessException("购物车商品不存在");
        }
        
        // 检查当前用户是否为购物车项的创建者
        String currentUserId = userService.getCurrentUser().getId();
        if (!existingItem.getCreator().equals(currentUserId)) {
            throw new BusinessException("无权修改他人的购物车商品");
        }
        
        // 更新字段
        existingItem.setType(updateDTO.getType());
        existingItem.setQuantity(updateDTO.getQuantity());
        
        return this.updateById(existingItem);
    }
}
